/**
 * @file ring_buffer.h
 * @brief 高性能环形缓冲区实现
 * 
 * 这个环形缓冲区实现针对高频交易系统的特殊需求进行了优化：
 * 1. 使用模板支持任意数据类型
 * 2. 固定大小设计避免动态内存分配
 * 3. 缓存行对齐以提高性能
 * 4. SPSC（单生产者单消费者）场景优化
 * 5. 无锁设计减少同步开销
 */

#pragma once

#include <array>
#include <atomic>
#include <cstddef>
#include <type_traits>

namespace hft {
namespace utils {

// 缓存行大小（字节）
constexpr size_t CACHE_LINE_SIZE = 64;

/**
 * @brief 缓存行对齐的原子计数器
 * 
 * 将读写指针放在不同的缓存行上，避免false sharing
 */
struct alignas(CACHE_LINE_SIZE) AlignedAtomicIndex {
    std::atomic<size_t> value{0};
    // 填充以确保整个结构体占用一个完整的缓存行
    char padding[CACHE_LINE_SIZE - sizeof(std::atomic<size_t>)];
};

/**
 * @brief 高性能环形缓冲区
 * 
 * @tparam T 存储的数据类型
 * @tparam N 缓冲区大小，必须是2的幂
 */
template<typename T, size_t N>
class RingBuffer {
    static_assert(N && !(N & (N - 1)), "Buffer size must be a power of 2");
    static_assert(std::is_trivially_copyable<T>::value, 
                  "Type must be trivially copyable for thread safety");

public:
    /**
     * @brief 尝试写入一个元素
     * 
     * @param value 要写入的值
     * @return true 写入成功
     * @return false 缓冲区已满
     */
    bool try_push(const T& value) noexcept {
        const size_t current_write = write_index_.value.load(std::memory_order_relaxed);
        const size_t next_write = (current_write + 1) & (N - 1);
        
        if (next_write == read_index_.value.load(std::memory_order_acquire)) {
            return false;  // 缓冲区已满
        }

        buffer_[current_write] = value;
        write_index_.value.store(next_write, std::memory_order_release);
        return true;
    }

    /**
     * @brief 尝试读取一个元素
     * 
     * @param value 输出参数，存储读取的值
     * @return true 读取成功
     * @return false 缓冲区为空
     */
    bool try_pop(T& value) noexcept {
        const size_t current_read = read_index_.value.load(std::memory_order_relaxed);
        
        if (current_read == write_index_.value.load(std::memory_order_acquire)) {
            return false;  // 缓冲区为空
        }

        value = buffer_[current_read];
        read_index_.value.store((current_read + 1) & (N - 1), 
                               std::memory_order_release);
        return true;
    }

    /**
     * @brief 检查缓冲区是否为空
     */
    bool empty() const noexcept {
        return read_index_.value.load(std::memory_order_relaxed) == 
               write_index_.value.load(std::memory_order_relaxed);
    }

    /**
     * @brief 检查缓冲区是否已满
     */
    bool full() const noexcept {
        const size_t next_write = (write_index_.value.load(std::memory_order_relaxed) + 1) 
                                 & (N - 1);
        return next_write == read_index_.value.load(std::memory_order_relaxed);
    }

    /**
     * @brief 获取当前缓冲区中的元素数量
     */
    size_t size() const noexcept {
        const size_t write = write_index_.value.load(std::memory_order_relaxed);
        const size_t read = read_index_.value.load(std::memory_order_relaxed);
        return (write - read) & (N - 1);
    }

    /**
     * @brief 获取缓冲区容量
     */
    constexpr size_t capacity() const noexcept {
        return N;
    }

    /**
     * @brief 清空缓冲区
     */
    void clear() noexcept {
        read_index_.value.store(0, std::memory_order_relaxed);
        write_index_.value.store(0, std::memory_order_relaxed);
    }

private:
    // 缓存行对齐的读写指针
    AlignedAtomicIndex read_index_;
    AlignedAtomicIndex write_index_;
    
    // 数据缓冲区
    alignas(CACHE_LINE_SIZE) std::array<T, N> buffer_;
};

} // namespace utils
} // namespace hft